package com.zzyl.wechat.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.wechat.service.WeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WeChatServiceImpl implements WeChatService {

    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String appsecret;

    private final static  String OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private final static  String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private final static  String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";


    @Override
    public String getopenID(String code) {
        HashMap<String,Object> params = getCommonParam();
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        String responseBody = HttpUtil.get(OPEN_ID_URL, params);
        System.out.println( "responseBody:"+responseBody);
        if(StrUtil.isBlank(responseBody)){
            throw new BaseException("获取openId失败");
        }
        JSONObject entries = JSONUtil.parseObj(responseBody);
        System.out.println( "getopenId:"+entries);
        return entries.getStr("openid");
    }

    @Override
    public String getPhone(String phoneCode) {
        String token = this.getACCESSToken();
        Map<String ,Object >params = Map.of("code",phoneCode);
        String responseBody = HttpUtil.post(PHONE_URL + token, JSONUtil.toJsonStr(params));
        System.out.println( "responseBody:"+responseBody);
        if (StrUtil.isBlank(responseBody)){
            throw new BaseException("获取手机号失败");
        }
        JSONObject entries = JSONUtil.parseObj(responseBody);
        System.out.println( "getPhone:"+entries);
        String phoneInfo = entries.getStr("phone_info");
        if (StrUtil.isNotBlank(phoneInfo)){
            JSONObject phoneInfoJson = JSONUtil.parseObj(phoneInfo);
            return phoneInfoJson.getStr("phoneNumber");
        }
        return null;
    }

    private HashMap<String ,Object> getCommonParam(){
        HashMap<String, Object> params = new HashMap<>();
        params.put("appid", this.appid);
        params.put("secret", this.appsecret);
        return params;
    }

    private String getACCESSToken(){
        HashMap<String,Object> params = getCommonParam();
        params.put("grant_type", "client_credential");
        String responseBody = HttpUtil.get(ACCESS_TOKEN_URL, params);
        if(StrUtil.isBlank(responseBody)){
            throw new BaseException("获取token失败");
        }
        JSONObject entries = JSONUtil.parseObj(responseBody);
        return entries.getStr("access_token");
    }
}
